/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.device.modular.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import vip.xiaonuo.device.core.enums.Constants;
import vip.xiaonuo.device.modular.entity.ApiLog;
import vip.xiaonuo.device.modular.entity.DevConfig;
import vip.xiaonuo.device.modular.mapper.ApiLogMapper;
import vip.xiaonuo.device.modular.mapper.DevConfigMapper;
import vip.xiaonuo.device.modular.service.TokenService;

import java.util.HashMap;
import java.util.Map;


/**
 * 设备api日志Service接口实现类
 *
 * @author levin
 * @date 2022/11/30 13:27
 **/
@ConfigurationProperties(prefix = "remote")
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private DevConfigMapper devConfigMapper;

    @Setter
    private String iotUrl;
    @Setter
    private String iotToken;

    @Autowired
    protected ApiLogMapper apiLogMapper;

    @Override
    public String getToken() {
        DevConfig devConfig = devConfigMapper.selectOne(new LambdaQueryWrapper<DevConfig>()
                .eq(DevConfig::getConfigKey, "GLOBAL_DEVICE_TOKEN")
                .last("limit 1"));
        Assert.notNull(devConfig, "GLOBAL_DEVICE_TOKEN未配置");
        Assert.notEmpty(devConfig.getConfigValue(), "GLOBAL_DEVICE_TOKEN值不能为空");
        return devConfig.getConfigValue();
    }

    @Override
    @Async("hxunicornAsyncServiceExecutor")
    public void handleDoorCallBack(ApiLog apiLog) {

        JSONObject body = new JSONObject();
        body.put("token", this.getToken());
        body.put("eqcode", apiLog.getCabinetCode());
        Map<String, Object> map = new HashMap<>();
        map.put("callback", (ObjectUtil.equal(apiLog.getReqType(), Constants.OPENDOOR) ? "open" : "close") + "-" + apiLog.getId());
        body.put("sensors", map);
        String bodyStr = body.toJSONString();
        String callbackUrl = iotUrl + "/api/sensor/smartSync";
        String resp = HttpRequest.post(callbackUrl).body(bodyStr).execute().body();

        //更新的实体类
        ApiLog entity = new ApiLog();
        //返回报文
        JSONObject respJson = JSONObject.parseObject(resp);
        if (respJson.getJSONObject("data") != null) {
            String respValue = respJson.getJSONObject("data").getString("value");
            entity.setEventId(respValue.substring(respValue.indexOf("-"), respValue.length()));
        }
        entity.setId(apiLog.getId());
        entity.setCallbackUrl(callbackUrl);
        entity.setCallbackReq(bodyStr);
        entity.setCallbackResp(resp);
        apiLogMapper.updateById(entity);
    }
}
